# !/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import json
from xtls.logger import get_logger

from company_xsb_handler import XsbBaseHandler
from cleaner import clean_str_null

reload(sys)
sys.setdefaultencoding('utf-8')


class ManagementHandler(XsbBaseHandler):
    def __init__(self, stock, data, tab_op):
        logger = get_logger(__file__)
        super(ManagementHandler, self).__init__(stock, data, tab_op, logger)
        self.tab_name = 'management'

    def parse(self):
        reasult = []

        if not self.data:
            return reasult

        for single in self.data:
            reasult.append(self.data_transfer(single))

        return reasult

    def data_transfer(self, data):
        db_data = dict()
        db_data['name'] = data.get('name', '')  # 高管姓名
        db_data['position'] = data.get('job', '').replace(u'、', ',')  # 职位
        db_data['birthYear'] = data.get('age', '')  # 出生年份（但是目前是当前的岁数,在清洗的时候转换）
        db_data['gender'] = data.get('gender', '')  # 性别
        db_data['degree'] = data.get('education', '')  # 学历

        return clean_str_null(db_data)

    def clean_data(self, dirty_data):
        self.cleaner.set_dirty_data(dirty_data)
        self.cleaner.clean_age_to_brith_year(['birthYear'])
        self.cleaner.clean_get_degree_id(['degree'], conn=self.conn)
        self.cleaner.clean_get_id_list(['position'], conn=self.conn)
        return self.cleaner.complete()

    def save_update(self, data):
        version_num = 1 + self.select_current_version_num(table_name=self.tab_name,
                                                          stock_id=self.stock.id)
        for single in data:
            if not single:
                self.logger.warn('management has no information %s-%s' % (self.stock.id, self.stock.stock_code))
                return
            if not self.stock.id:
                return

            single_clean = self.clean_data(single)
            single_clean['stockId'] = self.stock.id
            single_clean['versionNum'] = version_num
            self.insert_to_db(table_name=self.tab_name, cleaned_data=single_clean)

    def save_print(self, data):
        clean_data = self.clean_data(data)
        print json.dumps(clean_data, indent=4)
        # raw_input()

